package cn.xc.org.service.impl;

import cn.xc.basic.service.impl.BaseServiceImpl;
import cn.xc.org.domain.Department;
import cn.xc.org.mapper.DepartmentMapper;
import cn.xc.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Transactional
    @Override
    public void add(Department department) {
        departmentMapper.save(department);
        if(department.getParent_id()==null){
            department.setDirPath("/"+department.getId());
        }else {
            String parentDirPath = departmentMapper.loadById(department.getParent_id()).getDirPath();
            department.setDirPath(parentDirPath+"/"+department.getId());
        }

        departmentMapper.update(department);
    }



    @Transactional
    @Override
    public void update(Department department) {
        if(department.getParent_id()==null){
            department.setDirPath("/"+department.getId());
        }else {
            String parentDirPath = departmentMapper.loadById(department.getParent_id()).getDirPath();
            department.setDirPath(parentDirPath+"/"+department.getId());
        }
        departmentMapper.update(department);
    }

    @Override
    public void patchDel(List<Long> ids) {
        departmentMapper.patchDel(ids);
    }

    /**
     * 修改和新增無極樹
     * @return
     */
    @Override
    public List<Department> deptTree() {
        List<Department> departments = departmentMapper.loadAll();
        Map<Long, Department> map = new HashMap<>();
        for (Department department : departments) {
            map.put(department.getId(),department);
        }
        List<Department> deptTree = new ArrayList<>();
        for (Department department : departments) {
            if(department.getParent_id()==null){//顶级部门
                deptTree.add(department);
            }else {//不是顶级部门
                //获取当前部门的上级部门id
                Long parent_id = department.getParent_id();
                //上级部门对象
                Department parentDepartment = map.get(parent_id);
                //将自己装在上级部门的集合中
                parentDepartment.getChildren().add(department);
            }
        }
        return deptTree;
    }



}
